package com.banciyuan.bcywebview.biz.register;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.login.LoginActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.CommonApiUtils;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.NetUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PhoneRegisterActivity extends BaseActivity implements View.OnClickListener {
    private EditText mPhoneEt, mPwdEt, mNickNameEt, mCodeEt;
    private View mViewGetCode;
    private TextView mViewCountDown;
    private View ivPlain, ivSecret;
    private String phoneNum, nickName, codeNum, password;
    private RequestQueue mQueue;
    private int countdown_time = 60;
    private int REFRESH_COUNTDOWN = 100;
    private FrameLayout mRegisterPgb;
    private Boolean ifSina = false;
    private Boolean ifQQ = false;
    private String sinaName, qqName;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == REFRESH_COUNTDOWN) {
                if (countdown_time > 0) {
                    countdown_time--;
                    mViewCountDown.setText(String.format(getString(R.string.countdown_format), countdown_time));
                    mHandler.sendEmptyMessageDelayed(REFRESH_COUNTDOWN, 1000);
                } else {
                    mViewCountDown.setVisibility(View.GONE);
                    mViewGetCode.setVisibility(View.VISIBLE);
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.phone_register_layout);
        initArgs();
        initUi();
        initAction();
    }


    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
        ifSina = StringUtil.getBoolean(getIntent(), gotoUtil.INTENT_VALUE_ONE);
        ifQQ = StringUtil.getBoolean(getIntent(), gotoUtil.INTENT_VALUE_THREE);
        if (ifSina) {
            sinaName = StringUtil.getString(getIntent(), gotoUtil.INTENT_VALUE_TWO);
        } else if (ifQQ) {
            qqName = StringUtil.getString(getIntent(), gotoUtil.INTENT_VALUE_TWO);
        }
    }

    @Override
    protected void initUi() {
        mPhoneEt = (EditText) findViewById(R.id.et_phone);
        mNickNameEt = (EditText) findViewById(R.id.register_nickname_et);
        mPwdEt = (EditText) findViewById(R.id.register_pass_et);
        mCodeEt = (EditText) findViewById(R.id.et_auth_code);
        mViewGetCode = findViewById(R.id.view_code);
        mViewCountDown = (TextView) findViewById(R.id.view_code_countdown);
        ivPlain = findViewById(R.id.iv_plain);
        ivSecret = findViewById(R.id.iv_secret);
        mRegisterPgb = (FrameLayout) findViewById(R.id.register_register_progressbar);
    }

    @Override
    protected void initAction() {
        findViewById(R.id.tv_register).setOnClickListener(this);
        findViewById(R.id.iv_cancle_phone).setOnClickListener(this);
        findViewById(R.id.iv_close).setOnClickListener(this);
        findViewById(R.id.ll_login).setOnClickListener(this);
        ivPlain.setOnClickListener(this);
        ivSecret.setOnClickListener(this);
        mViewGetCode.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_register:
                if (!NetUtils.checkNetwork(this))
                    onNetworkError(getResources().getString(R.string.network_abnormal));
                else doRegister();
                break;
            case R.id.iv_close:
                gotoUtil.replaceActAmin(this, LoginActivity.class, R.anim.base_slide_left_in, R.anim.base_slide_right_out);
                break;
            case R.id.iv_cancle_phone:
                mPhoneEt.setText("");
                break;
            case R.id.iv_plain:
                ivPlain.setVisibility(View.GONE);
                ivSecret.setVisibility(View.VISIBLE);
                mPwdEt.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                break;
            case R.id.iv_secret:
                ivSecret.setVisibility(View.GONE);
                ivPlain.setVisibility(View.VISIBLE);
                mPwdEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                break;
            case R.id.view_code:
                phoneNum = mPhoneEt.getText().toString().trim();
                if (validPhone()) {
                    mViewGetCode.setVisibility(View.INVISIBLE);
                    mViewCountDown.setVisibility(View.VISIBLE);
                    countdown_time = 60;
                    mHandler.sendEmptyMessage(REFRESH_COUNTDOWN);
                    requestCode();
                }
                break;
            case R.id.ll_login:
                gotoUtil.replaceActAmin(this, LoginActivity.class, R.anim.base_slide_right_in, R.anim.base_slide_left_out);
                break;
        }
    }

    private void requestCode() {
        String url = HttpUtils.BASE_URL + UserApi.registerCode();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.MOBILE, phoneNum));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, PhoneRegisterActivity.this)) {
                        JSONObject result = new JSONObject(s);
                        MyToast.show(PhoneRegisterActivity.this, result.getString(HttpUtils.UPLOAD_DATA));
                    } else {
                        countdown_time = 0;
                        mHandler.sendEmptyMessage(REFRESH_COUNTDOWN);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        };
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, error);
        mQueue.add(stringRequest);
    }

    private boolean validPhone() {
        boolean matches = phoneNum.matches("^\\d{11}$");
        if (!matches) {
            MyToast.show(this, getString(R.string.unvalid_phonenum));
        }
        return matches;
    }

    private void doRegister() {
        mRegisterPgb.setVisibility(View.VISIBLE);
        if (validUserInfo()) {
            Response.Listener<String> onsuccess = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject result = new JSONObject(response);
                        if ("1".equals(result.getString("status"))) {
                            dealRegisterJson(response);
                        } else {
                            MyToast.show(PhoneRegisterActivity.this, result.getString(HttpUtils.UPLOAD_DATA));
                            mRegisterPgb.setVisibility(View.GONE);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        mRegisterPgb.setVisibility(View.GONE);
                    }
                }
            };
            Response.ErrorListener onError = new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    MyToast.show(PhoneRegisterActivity.this, getResources().getString(R.string.network_error));
                    mRegisterPgb.setVisibility(View.GONE);
                }
            };
            CommonApiUtils.doPhoneRegisterAction(this, mQueue, onsuccess, onError, phoneNum, password,
                    nickName, codeNum, ifSina, ifQQ, sinaName, qqName);
        }
    }

    public void dealRegisterJson(String result) {
        try {
            JSONObject response = new JSONObject(result);
            UserDataHelper.Login(response.getJSONObject(HttpUtils.UPLOAD_DATA), this);
            gotoUtil.replaceAct(this, RegisterChooseHeadActivity.class);
        } catch (JSONException e) {
            MyToast.show(this, getResources().getString(R.string.network_error));
            mRegisterPgb.setVisibility(View.GONE);
        }
    }

    private boolean validUserInfo() {
        nickName = mNickNameEt.getText().toString().trim();
        phoneNum = mPhoneEt.getText().toString().trim();
        codeNum = mCodeEt.getText().toString().trim();
        password = mPwdEt.getText().toString().trim();
        return !(!validPhone() || TextUtils.isEmpty(nickName) || TextUtils.isEmpty(codeNum) || TextUtils.isEmpty(password));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            gotoUtil.replaceActAmin(this, LoginActivity.class, R.anim.base_slide_left_in, R.anim.base_slide_right_out);
        }
        return true;
    }
}
